[C#] 使用API调用NLP词法分析

您所在的位置:网站首页 nlp 词法分析 [C#] 使用API调用NLP词法分析

[C#] 使用API调用NLP词法分析

#[C#] 使用API调用NLP词法分析| 来源: 网络整理| 查看: 265

在开发者Q群里有人反映不会使用API方式调用不了NLP词法分析, 昨晚试了一下, API还是没有坏的^_^ 虚惊一场

因为C#是最好的语言, 所以给大家看一下C#的调用demo.

1. 画一个图形界面

2. 执行步骤

        a. 使用两个Key换一个Token出来

        b. 使用Token和输入的语句, 发个POST请求, 换回结果.

        和大象进入冰箱有异曲同工之妙

 

3. 命名空间及引用 using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Http; using System.Text; using System.Web.Script.Serialization; using System.Windows.Forms;

  这里面使用了一个第三方的Newtonsoft.Json. 这个简直是神作. 可以去这里下载dll, 并且添加引用: https://www.newtonsoft.com/json

此外System.Web.Script这个在我的默认项目里面也没有, 需要手动添加.

 

4. 核心代码

      a. 两个Key换一个Token

     

public class AccessToken { // 百度云中开通对应服务应用的 API Key 建议开通应用的时候多选服务 private String clientId = ""; // 百度云中开通对应服务应用的 Secret Key private String clientSecret = ""; public AccessToken(string appkey, string secretkey) { this.clientId = appkey; this.clientSecret = secretkey; } // 调用getAccessToken()获取的 access_token建议根据expires_in 时间 设置缓存 // 返回token示例 //public static String TOKEN = "24.adda70c11b9786206253ddb70affdc46.2592000.1493524354.282335-1234567"; public String getAccessToken() { //这段照抄应该就可以 String authHost = "https://aip.baidubce.com/oauth/2.0/token"; HttpClient client = new HttpClient(); List> paraList = new List>(); paraList.Add(new KeyValuePair("grant_type", "client_credentials")); //两个Key在这里传进去 paraList.Add(new KeyValuePair("client_id", clientId)); paraList.Add(new KeyValuePair("client_secret", clientSecret)); HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result; String result = response.Content.ReadAsStringAsync().Result; //WARNING: 这个result不是单纯的token, 而是一大堆东西, 需要解析 return result; } }

从result中解析出来真正需要的token (我放到了点击Get Token那个按钮的点击事件里面了, 其实放别的地方也可以

private void button1_Click(object sender, EventArgs e) { AccessToken accToken = new AccessToken(this.textBoxAppKey.Text, this.textBoxSecretKey.Text); string returnedContent = accToken.getAccessToken(); //this result contains two parts (damned JSON file) //we have to split it into two parts and remove unnecessary suffix like brackets //Sample of return //"{\"access_token\":\"24.39d622b051970e1813476d643f62cadb.2592000.1515943229.282335-10477809\", //\"session_key\":\"9mzdCP1R5ugLlNT+jnWkhQDo78Lkn2O8x7j8XcrJ9gJTlfN7nxsY\\/F1WbTykpXZUZs8\\/mh1YRHl1dkQlNpL55fMwiQfebA==\", //\"scope\":\"iknow-antispam_spamauth public nlp_simnet nlp_wordemb nlp_comtag nlp_dnnlm_cn brain_nlp_lexer brain_all_scope brain_nlp_comment_tag brain_nlp_dnnlm_cn brain_nlp_word_emb_vec brain_nlp_word_emb_sim brain_nlp_sentiment_classify brain_nlp_simnet brain_nlp_depparser brain_nlp_wordembedding brain_nlp_dnnlm_cn_legacy brain_nlp_simnet_legacy brain_nlp_comment_tag_legacy brain_nlp_lexer_custom wise_adapt lebo_resource_base lightservice_public hetu_basic lightcms_map_poi kaidian_kaidian ApsMisTest_Test\\u6743\\u9650 vis-classify_flower bnstest_fasf lpq_\\u5f00\\u653e\", //\"refresh_token\":\"25.919a932d9db70b2b491050a8a2a1400b.315360000.1828711229.282335-10477809\", //\"session_secret\":\"51b4dabe72d9569f817f8fed4d517d17\",\"expires_in\":2592000}\n" Newtonsoft.Json.Linq.JObject obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(returnedContent); this.token = obj["access_token"].ToString(); this.label1.Text = this.token; }

     b. 有了token就可以正式调用NLP API了

public class AccessAPI { public string GetResultViaAPI(string strToken, string sentence) { //这里使用Token String apiHost = "https://aip.baidubce.com/rpc/2.0/nlp/v1/lexer?access_token=" + strToken; Dictionary para = new Dictionary(); //这里是真正的输入区 para.Add("text", sentence); //以下照抄 Encoding encoding = Encoding.GetEncoding("GBK"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(apiHost); request.Method = "post"; request.ContentType = "application/json"; request.KeepAlive = true; JavaScriptSerializer json = new JavaScriptSerializer(); String str = json.Serialize(para); byte[] buffer = encoding.GetBytes(str); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("GBK")); string result = reader.ReadToEnd(); return result; } }

 

最后来看一下运行效果:

 

好了, 就到这里~~~

 

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3